package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UsermanagerDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;

/**
 * @ProjectName: health_parent
 * @Package: com.itheima.service
 * @ClassName: UsermanagerServiceImpl
 * @Author: Torifu
 * @Date: 2019/7/5 11:59
 * @Description:  实现分页查询和搜索功能
 * @Version: 1.0
 */

@Service(interfaceClass = UsermanagerService.class)
public class UsermanagerServiceImpl implements UsermanagerService {

    @Autowired
    private UsermanagerDao usermanagerDao;

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        PageHelper.startPage(currentPage,pageSize);

        Page<User> page = usermanagerDao.selectByCondition(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(User user, Integer[] roleIds) {

        usermanagerDao.add(user);

        Integer userId = user.getId();
        setRelationBetweenUserAndRole(userId,roleIds);
    }

    @Override
    public void deleteById(Integer id) {

        deleteRelationBetweenUserAndRoleByUserId(id);

        usermanagerDao.deleteUserById(id);
    }

    @Override
    public User findUserById(Integer id) {

        User user = usermanagerDao.findUserById(id);

        return user;
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {

        return usermanagerDao.findRoleIdsByUserId(id);
    }

    @Override
    public void edit(User user, Integer[] roleIds) {

        deleteRelationBetweenUserAndRoleByUserId(user.getId());

        setRelationBetweenUserAndRole(user.getId(), roleIds);

        usermanagerDao.edit(user);
    }

    private void deleteRelationBetweenUserAndRoleByUserId(Integer id) {

        usermanagerDao.deleteUserAndRoleByUserId(id);
    }

    private void setRelationBetweenUserAndRole(Integer userId, Integer[] roleIds) {
        if (roleIds !=null && roleIds.length>0){
            for (Integer roleId : roleIds) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id",roleId);
                usermanagerDao.setUserIdAndRoleId(map);
            }
        }

    }
}
